using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class SkinSwiper : MonoBehaviour {
	
	UILabel focusLabel;
	
	List<UILabel> labels;

	// Use this for initialization
	void Start () {
		labels = new List<UILabel>();
		foreach(UISkin skin in GameReference.reference.skins)
		{
			UILabel label = NGUITools.AddWidget<UILabel>(gameObject);
			label.text = skin.name;
			label.font = GameReference.reference.skin.font;
			label.transform.localScale = Vector3.one * 40;
			label.pivot = UIWidget.Pivot.Center;
			label.transform.localPosition = Vector3.right * 120 * labels.Count;
			
			NGUITools.AddWidgetCollider(label.gameObject);
			
			((BoxCollider)label.collider).size = new Vector3(4, 2, 1);
			
			UIDragObject dragger = label.gameObject.AddComponent<UIDragObject>();
			
			dragger.target = gameObject.transform;
			dragger.scale = Vector3.right;
			
			labels.Add(label);
		}
		
		string savedSkin = PlayerPrefs.GetString("skin");
		
		if(string.IsNullOrEmpty(savedSkin))
			focusLabel = labels[Mathf.FloorToInt((labels.Count/2))];
		else
		{
			focusLabel = labels.Find(l => l.text == savedSkin);
		}
		
		findSkinByFocus();
		
		transform.localPosition = focusLabel.transform.localPosition * -1;
	}
	
	// Update is called once per frame
	void FixedUpdate () {
		
		if(Input.touchCount == 0 && !Input.GetMouseButton(0))
			transform.localPosition = Vector3.Lerp(transform.localPosition, focusLabel.transform.localPosition * -1, 0.1f);
		
		foreach(UILabel s in labels)
		{
			if(Mathf.Abs(s.transform.localPosition.x + transform.localPosition.x) < 20)
			{
				if(focusLabel != s)
				{
					focusLabel = s;
					findSkinByFocus();
				}
			}
		}
	}
	
	void findSkinByFocus()
	{
		foreach(UISkin s in GameReference.reference.skins)
		{
			if(s.name == focusLabel.text)
			{
				GameReference.reference.skin = s;
				GameReference.reference.SkinChangedStart = true;
				
				PlayerPrefs.SetString("skin", s.name);
				
				return;
			}
		}
	}
}
